package com.pig4cloud.pig.flow.intecepter;


import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.impl.identity.Authentication;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;
import java.util.UUID;

/**
 * @Author: hyk
 * @Date: 2024-2-19 10:45
 * @Description:
 */

public class LogInterceptor implements HandlerInterceptor {

	private static final String TRACE_ID = "TRACE_ID";

	private final IdentityService identityService;

	public LogInterceptor(IdentityService identityService) {
		this.identityService = identityService;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		Optional.ofNullable(SecurityUtils.getUser()).ifPresent(pigUser -> identityService.setAuthenticatedUserId(pigUser.getId().toString()));
		String tid = UUID.randomUUID().toString().replace("-", "");
		//可以考虑让客户端传入链路ID，但需保证一定的复杂度唯一性；如果没使用默认UUID自动生成
		if (!ObjectUtils.isEmpty(request.getHeader("TRACE_ID"))) {
			tid = request.getHeader("TRACE_ID");
		}
		MDC.put(TRACE_ID, tid);
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
								@Nullable Exception ex) {
		MDC.remove(TRACE_ID);
		identityService.clearAuthentication();
	}

}
